package tool;

import java.io.IOException;
import java.util.Objects;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class OfflineStateVerifyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        HttpSession session = req.getSession();
        int accountId = ObjectConverter.castObjectToInteger(session.getAttribute("account-id"));
        String accountName = (String) session.getAttribute("account-name");
        if (accountId > 0 && Objects.nonNull(accountName) && accountName.length() > 0) {
            String referer = req.getHeader("referer");
            if (accountId > 0 && Objects.nonNull(referer) && referer.length() > 0) {
                resp.sendRedirect(referer);
            } else {
                resp.sendRedirect("contact-handler");
            }
        } else {
            chain.doFilter(req, resp);
        }
    }
}
